//sMES Desktop Log Service
define(['angularAMD', 'moment'], function (angularAMD, moment) {
    angularAMD.factory('$LogService', ['config', '$rootScope', function(config, $rootScope){
        var service = {}, log, path, fs, isDesktop = false, fileTimeStamp = 'YYYYMMDDHH';
        function init(){
            if(window.nodeRequire){
                //Load common config from localstorage[SMES_log]
                var temp_log = JSON.parse(localStorage.getItem(config.appName + '_log'));
                if(temp_log != undefined && temp_log !== null)
                    config.log = temp_log;

                isDesktop = true;
                fs = window.nodeRequire('fs');
                path = window.nodeRequire('path');
                log = window.nodeRequire('electron-log');
                log.transports.file.level = config.log.level;
                log.transports.file.fileTime = moment().format(fileTimeStamp);
                // 20240321 modify by Alan for#159805 : electron-log升到V4，會多一個logs目錄
                log.transports.file.fileName =
                    log.transports.file.findLogPath.name === "deprecated"
                        ? `${ log.transports.file.fileTime }.log`
                        : `logs\\${ log.transports.file.fileTime }.log`;
                log.transports.file.maxSize = 1024*1024*config.log.maxSize;
                log.transports.file.archiveLog = function(filePath){
                    //var fileInfo = path.parse(filePath);
                    //log.transports.file.fileName = 'logs\\'+ moment().format('YYYYMMDD-HH')+'.log';
                    //fs.renameSync(filePath, path.join(fileInfo.dir, fileInfo.name + '.old' + fileInfo.ext));
                };

                log.transports.console.level = false;
                //取出log位置
                service.log_path = path.parse(log.transports.file.findLogPath()).dir;
                service.DeleteLogFiles();
            }

            return service;
        }

        //判斷是否要換一個檔案
        function FileRotate(callback){
            var nowTime = moment().format(fileTimeStamp);
            if(log.transports.file.fileTime == nowTime){
                callback();
            } else {
                log.transports.file.fileTime = nowTime;
                log.transports.file.fileName = 'logs\\'+ log.transports.file.fileTime+'.log';
                log.transports.file.file = service.log_path + '\\'+ log.transports.file.fileTime+'.log';
                log.transports.file.init();
                callback();
            }
        }

        service.log = function(msg){
            if(isDesktop){
                FileRotate(function(){
                    log.info(msg);
                });
            }
        };

        service.ServiceLog = function(uri, data){
            if(isDesktop){
                FileRotate(function(){
                    if ($rootScope.checkIsElectron()) {
                        log.info('[' + uri + '] ' + JSON.stringify(data));
                    }
                });
            }
        };

        service.SaveConfig = function(callback){
            localStorage.setItem(config.appName + '_log', JSON.stringify(config.log));
            if(callback)
                callback();
        };

        service.ToFile = function(isSave){
            log.transports.file.level = isSave;
        };

        service.ToDevConsole = function(isOutput){
            log.transports.console.level = isOutput;
        };

        //取得設定資料夾所有log檔案
        service.GetLogList = function(callback){
            $rootScope.showLoading();
            fs.readdir(service.log_path, function(err, files){
                if(err)
                    throw err;

                var log_list = [];
                files.forEach(function(file){
                    var file_path = service.log_path+'\\'+file;
                    var file_state = fs.statSync(file_path);
                    log_list.push({fileName: file, state: file_state});
                });
                $rootScope.hideLoading();
                if(callback)
                    callback(log_list);
            });
        };

        //取得log資料夾路徑
        service.GetLogPath = function(){
            var fileInfo = path.parse(log.transports.file.findLogPath());
            return fileInfo.dir;
        };

        service.OpenLogPath = function(){
            window.nodeRequire('child_process').exec('start "" "'+service.log_path+'"');
        };

        service.OpenLogFile = function(fileName){
            if(fileName == undefined){
                fileName = log.transports.file.findLogPath();
            } else {
                fileName = service.log_path+'\\'+fileName;
            }
            try {
                // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                const { shell } = window.nodeRequire('electron');
                shell.openItem ? shell.openItem(fileName) : shell.openPath(fileName);
            } catch (error) {
                nw.Shell.openItem(fileName);
            }
        };

        service.DeleteLogFile = function(fileName, callback){
            if(fileName == undefined){
                log.transports.file.clear();
            } else {
                $rootScope.showLoading();
                fileName = service.log_path+'\\'+fileName;
                fs.unlinkSync(fileName);
                $rootScope.hideLoading();
            }
            if(callback)
                callback();
        };

        service.DeleteLogFiles = function(options){
            if(isDesktop){
                options = options||{};
                if(options.callback)
                    $rootScope.showLoading();
                fs.readdir(service.log_path, function(err, files){
                    if(err){
                        if(options.callback){
                            $rootScope.hideLoading();
                            options.callback(err);
                        }
                    } else {
                        var min_stamp = moment().subtract(config.log.days, 'days').format(fileTimeStamp);
                        files.forEach(function(file){
                            if(options.isAll == true || min_stamp > path.parse(file).name){
                                service.DeleteLogFile(file);
                            }
                        });
                        if(options.callback){
                            $rootScope.hideLoading();
                            options.callback();
                        }
                    }
                });
            }
        };

        return init();
    }]);
});
